package com.rdc.qingkou.model;

import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.config.URL;
import com.rdc.qingkou.dto.CommentDTO;
import com.rdc.qingkou.dto.ResultDTO;
import com.rdc.qingkou.entity.User;
import com.rdc.qingkou.model.imodel.ITwoLevelCommentModel;
import com.rdc.qingkou.presenter.TwoLevelCommentPresenter;
import com.rdc.qingkou.retrofitService.ICommentService;
import com.rdc.qingkou.utils.MyUtils;
import com.rdc.qingkou.vo.CommentTwoLevelVO;
import com.rdc.qingkou.vo.UserVO;

import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;


public class TwoLevelCommentModel implements ITwoLevelCommentModel {

    private TwoLevelCommentPresenter presenter;
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    public TwoLevelCommentModel(TwoLevelCommentPresenter presenter) {
        this.presenter = presenter;
    }


    @Override
    public void clearDisposable() {
        mCompositeDisposable.dispose();
    }

    @Override
    public void addDisposable(Disposable disposable) {
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void appreciate(final int commentId) {
        MyUtils.getRetrofitProvider(URL.GET_APPRECIATE_COMMENT)
                .create(ICommentService.class)
                .appreciate(commentId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<ResultDTO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Response<ResultDTO> resultDTOResponse) {
                        if (resultDTOResponse.code() != HttpURLConnection.HTTP_OK) {
                            presenter.appreciateError("点赞/取消点赞失败！error code " + resultDTOResponse.code());
                        } else if (resultDTOResponse.body().isSuccess()) {
                            presenter.appreciateSuccess(commentId, resultDTOResponse.body().getMessage());
                        } else {
                            presenter.appreciateError("点赞/取消点赞失败！error code " + resultDTOResponse.code());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof SocketTimeoutException) {
                            presenter.appreciateError("连接超时！");
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void sendTwoLevelComment(final String input, final int userId, final int reviewerId, int parentCommentId, final String reviewer) {
        MyUtils.getRetrofitProvider(URL.POST_SEND_TWO_LEVEL_COMMENT).create(ICommentService.class)
                .sendTwoLevelComment(userId, input, parentCommentId, reviewerId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<ResultDTO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Response<ResultDTO> response) {
                        if (response.code() != HttpURLConnection.HTTP_OK) {
                            presenter.sendTwoLevelCommentError("发送评论失败! error code:" + response.code());
                        } else if (!response.body().isSuccess()) {
                            presenter.sendTwoLevelCommentError("发送评论失败! 原因:" + response.body().getReason());
                        } else {
                            CommentTwoLevelVO c = new CommentTwoLevelVO();
                            c.setPraiseNumber(0);
                            c.setCommentsNumber(0);
                            c.setPraise(false);
                            c.setContent(input);
                            UserVO userSend = new UserVO();
                            User user = MyApplication.getUser();
                            userSend.setUserId(user.getUserId());
                            userSend.setNickName(user.getNickName());
                            if (user.getImageUrl() == null) {
                                userSend.setHeadImageUrl(MyUtils.getUriFromDrawableRes(MyApplication.getContext(), R.drawable.pic6));
                            } else {
                                userSend.setHeadImageUrl(user.getImageUrl());
                            }
                            c.setUser(userSend);
                            if (reviewerId != 0) {
                                UserVO userReviewer = new UserVO();
                                userReviewer.setNickName(reviewer);
                                userReviewer.setUserId(userId);
                                c.setReviewer(userReviewer);
                            }
                            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            c.setCommentDate(dateFormatter.format(new Date()));
                            c.setCommentId(0);
                            presenter.sendTwoLevelCommentSuccess(c);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        presenter.getTwoLevelCommentError("发送评论失败！" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    @Override
    public void getTwoLevelComment(int commentId, int currentPage) {
        MyUtils.getRetrofitProvider(URL.GET_TWO_LEVEL_COMMENT).create(ICommentService.class)
                .getTwoLevelComment(commentId, currentPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<CommentDTO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Response<CommentDTO> response) {
                        //最新评论
                        if (response.code() != HttpURLConnection.HTTP_OK) {
                            presenter.getTwoLevelCommentError("获取评论失败！error code:" + response.code());
                            return;
                        }
                        presenter.getTwoLevelCommentSuccess(response.body().transformToTwoLevel());
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e.getMessage().equals("获取评论失败！")) {
                            presenter.getTwoLevelCommentError("获取评论失败！");
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
